package ua.kiev.tosik.price;

import org.apache.log4j.Logger;
import ua.kiev.tosik.price.conf.*;
import ua.kiev.tosik.price.gui.*;

import javax.swing.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Date;

import static org.pushingpixels.substance.api.SubstanceLookAndFeel.setSkin;

public class Main implements PropertyChangeListener {

	private static Logger logger = Logger.getLogger("ua.kiev.tosik.price");
	public static Date startDate;
	private SplashWindow splashWindow;
	public static DbConfig dbConfig;
	public static SkinType skinType;
	// public static final String M_ID;

//	static {
//		M_ID = getMotherboardSN();
//	}

	public Main() {
		// logger.debug("Initialize Main class. Motherboard Id: " + M_ID);
		splashWindow = new SplashWindow();
		splashWindow.setVisible(true);
		AdminLoaderWorker adminLoaderWorker = new AdminLoaderWorker();
		adminLoaderWorker.addPropertyChangeListener(splashWindow);
		adminLoaderWorker.addPropertyChangeListener(this);
		adminLoaderWorker.execute();

		dbConfig = DbConfig.getInstance();
		/*
		for (Object o : dbConfig.getEp().keySet()) {
			String k = (String) o;
			String value = dbConfig.get(k);
			logger.debug("   " + k + "=" + value);
		} */
		/*
		dbConfig.set("derby.dbname", "Prices");
		dbConfig.set("derby.user", "test");
		dbConfig.set("derby.password", "test");
		dbConfig.set("derby.system.home", "./db");
		*/
	}

	public static void main(String[] args) {
		System.setProperty("derby.system.home", "./db");
		startDate = new Date();
		JFrame.setDefaultLookAndFeelDecorated(true);
		JDialog.setDefaultLookAndFeelDecorated(true);
		SwingUtilities.invokeLater( new Runnable() {
			@Override
			public void run() {
				new Main();
			}
		});
	}

	public static void switchSkin(Skin skin) {
		try {
			logger.debug("Switch skin to new: " + skin.getName());
			setSkin(skin.getClassName());
			SkinsConfig.getInstance().setDefaultSkin(skin);
			skinType = SkinType.SUBSTANCE;
		} catch (Exception e) {
			logger.fatal("Can't apply Skin!", e);
		}
	}

	public static void switchSkin() {
		logger.debug("Switch skin to: " + SkinsConfig.getInstance().getDefaultSkin().getName());
		try {
			setSkin(SkinsConfig.getInstance().getDefaultSkin().getClassName());
			skinType = SkinType.SUBSTANCE;
		} catch (Exception e) {
			logger.fatal("Can't apply Skin!", e);
		}
	}

	@SuppressWarnings("unused")
	public void switchSystemSkin() {
		logger.debug("Setting System LookAndFeel");
		try {
			UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
			skinType = SkinType.SYSTEM;
			// UIManager.setLookAndFeel("com.jgoodies.looks.plastic.PlasticXPLookAndFeel");
		} catch (Exception e) {
			logger.warn("Can't apply Skin! " + e.getLocalizedMessage());
			try {
				UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
				// UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
				// UIManager.setLookAndFeel("org.fife.plaf.Office2003.Office2003LookAndFeel");
				// UIManager.setLookAndFeel("org.fife.plaf.OfficeXP.OfficeXPLookAndFeel");
				//UIManager.setLookAndFeel("org.fife.plaf.VisualStudio2005.VisualStudio2005LookAndFeel");
				// UIManager.setLookAndFeel("com.jgoodies.looks.windows.WindowsLookAndFeel");
				skinType = SkinType.SYSTEM;
			} catch (Exception ex) {
				logger.warn("Can't apply next Skin! " + e.getLocalizedMessage());
			}
		}
	}

	public static String getAppWorkTime(long timeMillis) {
		long time = (timeMillis-startDate.getTime()) / 1000;
		String seconds = Integer.toString((int) (time % 60));
		String minutes = Integer.toString((int) ((time % 3600) / 60));
		String hours = Integer.toString((int) (time / 3600));
		for (int i = 0; i < 2; i++) {
			if (seconds.length() < 2) {
				seconds = "0" + seconds;
			}
			if (minutes.length() < 2) {
				minutes = "0" + minutes;
			}
			if (hours.length() < 2) {
				hours = "0" + hours;
			}
		}
		// logger.debug("Application working time: " + hours + ":" + minutes + ":" + seconds);
		return hours + ":" + minutes + ":" + seconds;
	}

	public static long getUsedMemory() {
		// gc();
		long totalMemory = Runtime.getRuntime().totalMemory();
		// gc();
		long freeMemory = Runtime.getRuntime().freeMemory();
		// long usedMemory = totalMemory - freeMemory;
		return (totalMemory - freeMemory);
	}

	public static void gc() {
		try {
			System.gc();
			Thread.currentThread().sleep(100);
			System.runFinalization();
			Thread.currentThread().sleep(100);
			System.gc();
			Thread.currentThread().sleep(100);
			System.runFinalization();
			Thread.currentThread().sleep(100);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	@Override
	public void propertyChange(PropertyChangeEvent evt) {
		if ( evt.getPropertyName().equals("SwitchSkin") ) {
			switchSkin();
			//switchSystemSkin();
		}
		if ( evt.getPropertyName().equals("Done") ) {
			if ( (Boolean)evt.getNewValue() ) {
				logger.debug("Done with app config loader");
				splashWindow.setVisible(true);
				CreateGuiComponentsWorker createGuiComponentsWorker = new CreateGuiComponentsWorker();
				createGuiComponentsWorker.addPropertyChangeListener(splashWindow);
				createGuiComponentsWorker.addPropertyChangeListener(this);
				createGuiComponentsWorker.execute();
			} else {
				logger.error("Done with error");
			}
		}

		if ( evt.getPropertyName().equals("CreateMenu") ) {
			MainMenu.getInstance();
		}
		if ( evt.getPropertyName().equals("CreateStatus") ) {
			StatusBar.getInstance();
		}
		if ( evt.getPropertyName().equals("CreateTaskPanel") ) {
			TaskMenuPanel.getInstance();
		}
		if ( evt.getPropertyName().equals("CreateTabPanel") ) {
			CenterPanel.getInstance();
		}
		if ( evt.getPropertyName().equals("RunMainWindow") ) {
			MainWindow mainWindow = MainWindow.getInstance();
			mainWindow.getFrame().setVisible(true);
			splashWindow.destroy();
			splashWindow = null;
		}
	}

//	public static String getMotherboardSN() {
//		String result = "";
//		try {
//			File file = File.createTempFile("realhowto", ".vbs");
//			file.deleteOnExit();
//			FileWriter fw = new java.io.FileWriter(file);
//
//		String vbs =
//			"Set objWMIService = GetObject(\"winmgmts:\\\\.\\root\\cimv2\")\n"
//			+ "Set colItems = objWMIService.ExecQuery _ \n"
//			+ "   (\"Select * from Win32_BaseBoard\") \n"
//			+ "For Each objItem in colItems \n"
//			+ "    Wscript.Echo objItem.SerialNumber \n"
//			+ "    exit for  ' do the first cpu only! \n"
//			+ "Next \n";
//			fw.write(vbs);
//			fw.close();
//			Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
//			BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
//			String line;
//			while ((line = input.readLine()) != null) {
//				result += line;
//			}
//			input.close();
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return result.trim();
//	}

}
